﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Wicresoft.SMS.Data
{
    public class sqlWebSendDataAccess : ISendWebDataAccess
    {


        private IConnectStringProvider _connParamProvider;
         private string _connectionString;

         public sqlWebSendDataAccess(string ConnectionString)
        {
            _connectionString = ConnectionString;
        }

         public int SendSms(string addresslist, string smsContent, string UserName)
         {
             System.Data.Objects.ObjectParameter outs = new System.Data.Objects.ObjectParameter("outs", System.Data.DbType.Int32);
             try
             {
                 using (var dbModel = new Entities(_connectionString))
                 {
                     string[] addrs = addresslist.Split(';');
                     string to = "";
                     foreach (var item in addrs)
                     {
                         if (item == "")
                             continue;
                         if (!item.TrimStart().StartsWith("[G]"))
                             to += item + ";";
                         else
                         {
                             string strgroup = item.TrimStart();
                             strgroup = strgroup.Substring(3);

                             var user = dbModel.User.FirstOrDefault(u => u.CIL == UserName);
                             var group = dbModel.Group.FirstOrDefault(g => g.GroupName == strgroup && g.User.UserID == user.UserID);

                             foreach (var contact in group.Contact)
                             {
                                 to += contact.DisplayName + ";";
                             }
                         }
                     }


                     dbModel.cp_send_sms(UserName, smsContent, to, outs);
                     dbModel.SaveChanges();
                 }
             }
             catch (Exception ex)
             {
                 System.Diagnostics.Debug.WriteLine(ex.Message);
                 return -1;
             }
             return Convert.ToInt32(outs.Value);
         }


         public string forwardmessage(int Id)
         {
             using (var dbModel = new Entities(_connectionString))
             {
                 var m = dbModel.Message.FirstOrDefault(c => c.ID == Id);
                 return m.Content;
             }
             throw new NotImplementedException();
         }
    }
}
